package com.ckd.flyingtrip.activity;

import android.annotation.SuppressLint;
import android.util.Log;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.ckd.flyingtrip.constants.Constants;
import com.ckd.flyingtrip.javabean.PayReqBean;
import com.ckd.flyingtrip.javabean.WeixinBean;
import com.ckd.flyingtrip.utils.BcUtils;
import com.ckd.flyingtrip.utils.DataCheck;
import com.ckd.flyingtrip.utils.MD5;
import com.ckd.flyingtrip.utils.MD5Util;
import com.ckd.flyingtrip.widge.SingleVolleyRequestQueue;
import com.google.gson.Gson;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.SortedMap;

public class Weixin {
    private BaseActivity context;
    private String money_fell;
    private WeixinBean weixinBean;
    private IWXAPI api;
    private PayReqBean payReqBean;

    private PayReq req;
    Weixin(BaseActivity context, String money_fell){
        this.context = context;
        this.money_fell = money_fell;
        api = WXAPIFactory.createWXAPI(Objects.requireNonNull(context), Constants.APPID, false);;

    }




    /*
     * 套餐购买订单
     * */
    public void volleyDINGDAN(String id) {
        Gson gson = new Gson();
        final String url = Constants.ZHUCHE;
        StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                Log.i("我的订单", s);
                try {
                    Log.i("调取微信获取", s);
                    //s为请求返回的字符串数据
                        JSONObject json = new JSONObject(s);
                        String code = json.getString("code");
                    if(code.equals("0")){
                        context.toast(json.getString("message"));
                        context.dismisProgressDialog();
                        return;
                    }
                        if (code.equals("1")) {
                            String dataInfo = json.getString("data");
                            payReqBean = gson.fromJson(dataInfo, PayReqBean.class);
                            PayReq req = new PayReq();
                            req.packageValue = payReqBean.getPackageValue();
                            req.appId = payReqBean.getAppid();
                            req.partnerId = payReqBean.getPartnerid();
                            req.sign = payReqBean.getSign();
                            req.timeStamp = payReqBean.getTimestamp();
                            req.prepayId = payReqBean.getPrepayid();
                            req.nonceStr = payReqBean.getNoncestr();
                            api.sendReq(req);

                        }

                    context.dismisProgressDialog();
                } catch (JSONException e) {
                    e.printStackTrace();
                    context.dismisProgressDialog();
                }
                // 获取之对象的所有属性
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {//请求失败回调

                context.dismisProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {//创建请求参数
                HashMap<String, String> map = new HashMap<String, String>();
                JSONObject json_url = new JSONObject();
                try {
                    json_url.put("bicycleId", id);
                    json_url.put("userId", BcUtils.getUid());
                    json_url.put("payWay","2");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                map.put("inputParameter", DataCheck.signCheck(json_url.toString()));
                return map;
            }
        };
        SingleVolleyRequestQueue.getInstance(context).addToRequestQueue(request);
    }



    private long genTimeStamp() {
        return System.currentTimeMillis() / 1000;
    }




    /**
     * 获取sign签名
     *
     * @return
     */
//    private Map<Object, Object> genPayReq() {
//
//        // 获取参数的值
//        PayReq   request = new PayReq();
//        request.appId = Constants.APPID;
//        request.partnerId = weixinBean.getMch_id();
//        request.prepayId= weixinBean.getPrepay_id();
//        request.packageValue = "Sign=WXPay";
//        request.nonceStr= weixinBean.getNonce_str();
//        request.timeStamp=  String.valueOf(genTimeStamp());
//        // 把参数的值传进去SortedMap集合里面
//        SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
//
//        parameters.put("appid", request.appId);
//        parameters.put("noncestr", request.nonceStr);
//        parameters.put("package", request.packageValue);
//        parameters.put("partnerid", request.partnerId);
//        parameters.put("prepayid", request.prepayId);
//        parameters.put("timestamp", request.timeStamp);
//
//        String characterEncoding = "UTF-8";
//        String sign = createSign(characterEncoding, parameters);
//        parameters.put("sign", sign);
//        request.sign= sign;
//        api.sendReq(request);
//        return parameters;
//    }


    private void genPayReq() {
        req = new PayReq();
        req.appId = weixinBean.getAppid();
        req.partnerId = weixinBean.getMch_id();
        req.prepayId= weixinBean.getPrepay_id();
        req.packageValue = "Sign=WXPay";
        req.nonceStr= weixinBean.getNonce_str();
        req.timeStamp=  String.valueOf(genTimeStamp());

        List<NameValuePair> signParams = new LinkedList<NameValuePair>();
        signParams.add(new BasicNameValuePair("appid", req.appId));
        Log.i("微信id",req.appId+"------------");
        signParams.add(new BasicNameValuePair("noncestr", req.nonceStr));
        /**
         * 这里的package参数值必须是Sign=WXPay,否则IOS端调不起微信支付，
         * (参数值是"prepay_id="+resultunifiedorder
         * .get("prepay_id")的时候Android可以，IOS不可以)
         */
        signParams.add(new BasicNameValuePair("package", req.packageValue));
        /** 注意二次签名这里不再是mch_id,变成了prepayid; */
        signParams.add(new BasicNameValuePair("partnerid", req.partnerId));
        signParams.add(new BasicNameValuePair("prepayid", req.prepayId));
        signParams.add(new BasicNameValuePair("timestamp", req.timeStamp));

        req.sign = genAppSign(signParams);
        api.registerApp(weixinBean.getAppid());
        api.sendReq(req);

        context.dismisProgressDialog();
    }



    @SuppressLint("DefaultLocale")
    private String genAppSign(List<NameValuePair> params) {
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < params.size(); i++) {
            sb.append(params.get(i).getName());
            sb.append('=');
            sb.append(params.get(i).getValue());
            sb.append('&');
        }
        sb.append("key=");
        sb.append(weixinBean.getApi_key());

        String appSign = MD5.getMessageDigest(sb.toString().getBytes())
                .toUpperCase();
        Log.e("orion-appSign-->", appSign);
        return appSign;
    }




    /**
     * 微信支付签名算法sign
     *
     * @param characterEncoding
     * @param parameters
     * @return
     */
    public String createSign(String characterEncoding,
                                    SortedMap<Object, Object> parameters) {

        StringBuffer sb = new StringBuffer();
        Set es = parameters.entrySet();// 所有参与传参的参数按照accsii排序（升序）
        Iterator it = es.iterator();
        while (it.hasNext()) {
            @SuppressWarnings("rawtypes")
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            Object v = entry.getValue();
            if (null != v && !"".equals(v) && !"sign".equals(k)
                    && !"key".equals(k)) {
                sb.append(k + "=" + v + "&");
            }
        }
        sb.append("key=" + weixinBean.getApi_key()); //KEY是商户秘钥
        String sign = MD5Util.MD5Encode(sb.toString(), characterEncoding)
                .toUpperCase();
        return sign;
    }
}
